<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>收银台</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <link rel="stylesheet" href="/app/admin/component/layui/css/layui.css" />
    <script src="/app/admin/component/layui/layui.js"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <style>
        body {
            padding-top: 60px; /* 为顶部导航栏预留空间 */
        }
        .cashier-container {
            padding: 15px 15px 15px 75px;
            display: flex;
            height: calc(100vh - 140px); /* 调整高度，减去顶部导航栏的高度 */
            background: #f2f2f2;
        }
        .left-panel {
            width: 65%;
            margin-right: 15px;
            display: flex;
            flex-direction: column;
        }
        .right-panel {
            width: 35%;
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            display: flex;
            flex-direction: column;
        }
        .goods-panel {
            flex: 1;
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            overflow: auto;
        }
        .member-panel {
            height: 180px;  /* 减小整体高度 */
            background: #fff;
            padding: 10px;
            border-radius: 4px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        .cart-items {
            flex: 1;
            overflow: auto;
            margin: 10px 0;
        }
        .cart-footer {
            border-top: 1px solid #eee;
            padding-top: 10px;
        }
        .goods-item {
            display: inline-block;
            width: 120px;
            height: 120px;
            margin: 5px;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
            text-align: center;
            cursor: pointer;
            position: relative;
            background: #fff;
        }
        .goods-item:hover {
            border-color: #00BCD4;
        }
        .goods-name {
            margin-top: 5px;
            height: 40px;
            line-height: 20px;
            overflow: hidden;
            font-size: 12px;
        }
        .goods-price {
            color: #ff6b6b;
            font-size: 16px;
            font-weight: bold;
        }
        .member-info {
            display: none;
            background: #f8f8f8;
            border-radius: 2px;
            padding: 5px;
        }
        .member-info p {
            margin-bottom: 8px;
            line-height: 24px;
        }
        .member-info span {
            color: #009688;
            font-weight: bold;
            margin-left: 5px;
        }
        .search-bar {
            margin-bottom: 10px;
        }
        .category-bar {
            margin-bottom: 10px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .layui-table {
            margin: 0;
        }
        .layui-form-radio {
            margin: 0;
            padding: 8px;
        }
        .layui-table td, .layui-table th {
            padding: 9px 5px;
        }
        .btn-quantity {
            padding: 0 8px;
        }
        .customer-info {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}
.customer-text {
    margin-left: 10px;
}
.customer-name {
    font-size: 16px;
    font-weight: bold;
}
.customer-type {
    color: #999;
    font-size: 14px;
}
.payment-info {
    background: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
}
.amount-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}
.amount-row:last-child {
    margin-bottom: 0;
}
.payment-methods {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
}
.method-item {
    text-align: center;
    padding: 10px 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
}
.method-item.selected {
    background: #009688;
    color: white;
    border-color: #009688;
}
.number-pad {
    width: 100%;
}
.quick-amounts {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-bottom: 10px;
}
.amount-btn {
    padding: 10px;
    border: 1px solid #ddd;
    background: white;
    border-radius: 4px;
    cursor: pointer;
}
.num-btn[data-num="clear"],
.num-btn[data-num="backspace"],
.num-btn[data-num="enter"] {
    background-color: #f2f2f2;
}
.num-btn[data-num="enter"] {
    background-color: #009688;
    color: white;
}
.number-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-top: 15px;
}
.num-btn {
    padding: 15px;
    border: 1px solid #ddd;
    background: white;
    border-radius: 4px;
    cursor: pointer;
}
.num-btn:hover, .amount-btn:hover {
    background: #f2f2f2;
}
.method-item.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
        /* 会员查询区域样式 */
        .member-search-box {
            display: flex;
            align-items: center;
            background: #fff;
            padding: 8px;
            border-radius: 4px;
            margin-bottom: 5px;
            border-bottom: 1px solid #f0f0f0;
            justify-content: space-between;
        }
        .search-container {
            display: flex;
            align-items: center;
            width: calc(100% - 65px); /* 减去查询按钮的宽度 */
        }
        .search-type-group {
            display: flex;
            align-items: center;
            margin-right: 10px;
            white-space: nowrap;
            min-width: 140px; /* 确保搜索类型有足够空间 */
        }
        .search-type-group .layui-form-radio {
            margin: 0 10px 0 0;
            padding: 4px;
        }
        .search-type-group .layui-form-radio * {
            font-size: 13px;
        }
        .search-input-group {
            flex: 1;
            display: flex;
            align-items: center;
            max-width: calc(100% - 150px); /* 限制输入框最大宽度 */
        }
        .search-input {
            height: 30px;
            line-height: 30px;
            width: 100%;
        }
        .member-info-box {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 4px;
            display: none;
            margin-bottom: 15px;
            flex: 1;
            overflow: auto;
        }
        .member-info-row {
            display: flex;
            margin-bottom: 10px;
            padding: 0 10px;
        }
        .member-info-item {
            flex: 1;
            display: flex;
            align-items: center;
        }
        .member-info-label {
            color: #666;
            width: 80px;
            text-align: right;
            margin-right: 10px;
        }
        .member-info-value {
            color: #009688;
            font-weight: bold;
            flex: 1;
        }
        /* 收银弹窗样式优化 */
        .payment-dialog {
            padding: 15px;
        }
        .payment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 10px 15px;
            background: #f8f8f8;
            border-radius: 4px;
        }
        .customer-info {
            flex: 1;
            margin: 0;
        }
        .amount-info {
            flex: 1;
            text-align: right;
        }
        .amount-info .amount-item {
            margin-left: 20px;
            display: inline-block;
        }
        .amount-info .amount-label {
            color: #666;
            margin-right: 5px;
        }
        .amount-info .amount-value {
            color: #009688;
            font-weight: bold;
        }
        .payment-methods {
            margin: 15px 0;
            display: flex;
            gap: 10px;
        }
        .method-item {
            flex: 1;
            padding: 8px;
            text-align: center;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            cursor: pointer;
        }
        .number-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            margin-top: 10px;
        }
        .num-btn {
            padding: 10px;
            font-size: 14px;
        }
        .verify-code-area {
            display: flex;
            align-items: center;
            margin-top: 5px;
        }
        .verify-code-area .layui-btn {
            height: 32px;
            line-height: 32px;
            padding: 0 10px;
            font-size: 14px;
            min-width: 95px;
        }
        .verify-code-area .layui-input {
            height: 32px;
            line-height: 32px;
            padding: 0 5px;
            font-size: 14px;
        }
        .verify-code-area .layui-input-inline {
            width: 120px !important;
        }
        .verify-code-area .layui-form-label {
            height: 32px;
            line-height: 32px;
            font-size: 14px;
            padding: 0 8px;
        }
        .member-info .layui-form-item {
            margin-bottom: 5px;  /* 减小表单项之间的间距 */
        }
        
        .member-info .layui-form-label {
            width: 85px;  /* 减小标签宽度 */
            padding: 2px 5px;  /* 减小内边距 */
            font-size: 13px;
            line-height: 20px;
            height: 20px;
        }
        
        .member-info .layui-input-inline {
            width: 110px;
            height: 24px;
            line-height: 24px;
        }
        
        .member-info .layui-input {
            height: 24px;
            line-height: 24px;
            font-size: 13px;
        }
        
        .member-info-row {
            display: flex;
            justify-content: space-between;
        }
        
        .member-info-col {
            width: 48%;  /* 设置列宽 */
            height: 20px;
        }
        .layui-form-item{
            height: 20px; line-height: 20px;
        }
        /* 查询按钮样式 */
        .member-search-box .layui-btn {
            height: 30px;
            line-height: 30px;
            padding: 0 15px;
        }
    </style>
    <script>
        // 检查页面是否正常加载
        if (window.performance && window.performance.navigation.type === 2) {
            // 如果是从历史记录加载的页面，则刷新
            window.location.reload();
        }
    </script>
</head>
<body>
    <?php include base_path() . '/plugin/ky_shouyin/app/view/layout/topmenu.html'; ?>
    <?php include base_path() . '/plugin/ky_shouyin/app/view/layout/front_leftmenu.html'; ?>
    
    <div class="cashier-container">
        <!-- 左侧面板 -->
        <div class="left-panel">
            <!-- 商品展示区 -->
            <div class="goods-panel">
                <!-- 搜索栏 -->
                <div class="search-bar">
                    <div class="layui-input-inline" style="width: 300px;">
                        <input type="text" id="searchGoods" placeholder="输入商品名称/编码搜索" class="layui-input">
                    </div>
                </div>
                <!-- 分类栏 -->
                <div class="category-bar">
                    <button class="layui-btn layui-btn-primary layui-btn-sm" data-id="">全部</button>
                </div>
                <!-- 商品列表 -->
                <div id="goodsList"></div>
            </div>
            
            <!-- 会员信息区 -->
            <div class="member-panel">
                <!-- 会员查询区域 -->
                <div class="member-search-box">
                    <div class="search-container">
                        <div class="search-type-group">
                            <div class="layui-form">
                                <input type="radio" name="search_type" value="card" title="会员卡" checked lay-filter="searchType">
                                <input type="radio" name="search_type" value="phone" title="手机号" lay-filter="searchType">
                            </div>
                        </div>
                        <div class="search-input-group">
                            <input type="text" class="layui-input search-input" value="VIP" placeholder="请输入会员卡号">
                        </div>
                    </div>
                    <button class="layui-btn" id="searchMemberBtn">查询</button>
                </div>
                
                <!-- 会员信息显示区域 -->
                <div class="member-info" style="display: none;">
                    <input type="hidden" id="memberId" name="member_id">
                    <!-- 验证码区域 -->
                    <div class="layui-form-item verify-code-area" style="margin-bottom: 0;">
                        <label class="layui-form-label">验证码：</label>
                        <div class="layui-input-inline">
                            <input type="text" id="verifyCode" class="layui-input" placeholder="请输入验证码">
                        </div>
                        <button type="button" class="layui-btn layui-btn-primary" id="sendCode">发送验证码</button>
                    </div>
                    
                    <!-- 会员信息分两列显示 -->
                    <div class="member-info-row">
                        <div class="member-info-col">
                            <div class="layui-form-item" style="margin-bottom: 3px;">
                                <label class="layui-form-label">会员卡号：</label>
                                <div class="layui-input-inline">
                                    <span id="memberCardNo"></span>
                                </div>
                            </div>
                        </div>
                        <div class="member-info-col">
                            <div class="layui-form-item" style="margin-bottom: 3px;">
                                <label class="layui-form-label">会员姓名：</label>
                                <div class="layui-input-inline">
                                    <span id="memberName"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="member-info-row">
                        <div class="member-info-col">
                            <div class="layui-form-item" style="margin-bottom: 3px;">
                                <label class="layui-form-label">账户余额：</label>
                                <div class="layui-input-inline">
                                    <span id="memberBalance"></span>
                                </div>
                            </div>
                        </div>
                        <div class="member-info-col">
                            <div class="layui-form-item" style="margin-bottom: 3px;">
                                <label class="layui-form-label">会员积分：</label>
                                <div class="layui-input-inline">
                                    <span id="memberPoints"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧面板 -->
        <div class="right-panel">
            <!-- 购物车 -->
            <div class="cart-items">
                <table class="layui-table" lay-skin="nob">
                    <thead>
                        <tr>
                            <th>商品</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="cartList"></tbody>
                </table>
            </div>
            
            <!-- 结算区 -->
            <div class="cart-footer">
                <div class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">支付方式</label>
                        <div class="layui-input-block">
<!--                            <input type="radio" name="payment" value="cash" title="现金" checked>-->
                          <!-- <input type="radio" name="payment" value="wechat" title="微信"> -->
                            <!-- <input type="radio" name="payment" value="alipay" title="支付宝">   -->
                            <input type="radio" name="payment" value="balance" title="余额" disabled>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品合计</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input" id="totalAmount" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">优惠金额</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input" id="discountAmount" value="0">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">实收金额</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input" id="actualAmount" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="submitOrder" id="submitBtn">提交订单</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
<!-- ... 在页面底部添加收款确认弹窗模板 ... -->
<div id="paymentConfirmDialog" style="display: none;" class="payment-dialog">
    <div class="layui-form">
        <div class="payment-header">
            <div class="customer-info">
                <div class="member-info" style="display:none">
                    <span class="member-name"></span>
                    <span class="member-card" style="color: #666; margin-left: 10px;"></span>
                </div>
                <div class="guest-info">散客</div>
            </div>
        </div>
        
        <div class="amount-info">
            <div class="amount-item">
                <span class="amount-label">应收</span>
                <span class="pending-amount amount-value">¥0</span>
            </div>
            <div class="amount-item">
                <span class="amount-label">优惠</span>
                <span class="discount-amount amount-value">¥0</span>
            </div>
            <div class="amount-item">
                <span class="amount-label">实收</span>
                <input type="text" class="actual-amount layui-input" value="0" style="width:100px;display:inline-block">
            </div>
        </div>

<!--        <div class="payment-methods"   >-->
<!--            <div class="method-item" data-method="balance">-->
<!--                <i class="layui-icon layui-icon-user"></i>-->
<!--                <span>余额</span>-->
<!--            </div>-->
<!--            <div class="method-item selected" data-method="cash">-->
<!--                <i class="layui-icon layui-icon-rmb"></i>-->
<!--                <span>现金</span>-->
<!--            </div>-->

<!--        </div>-->

        <div class="number-pad">
            <div class="number-grid">
                <button class="num-btn" data-num="clear">清空</button>
                <button class="num-btn" data-num="backspace">退格</button>
<!--                <button class="num-btn" data-num="enter">确认</button>-->
                <button class="num-btn" data-num="1">1</button>
                <button class="num-btn" data-num="2">2</button>
                <button class="num-btn" data-num="3">3</button>
                <button class="num-btn" data-num="4">4</button>
                <button class="num-btn" data-num="5">5</button>
                <button class="num-btn" data-num="6">6</button>
                <button class="num-btn" data-num="7">7</button>
                <button class="num-btn" data-num="8">8</button>
                <button class="num-btn" data-num="9">9</button>
                <button class="num-btn" data-num="0">0</button>
                <button class="num-btn" data-num="00">00</button>
                <button class="num-btn" data-num=".">.</button>
            </div>
        </div>
        <div class="payment-actions" style="margin-top: 15px; text-align: center;">
            <button class="layui-btn layui-btn-lg layui-btn-normal" id="btnConfirmPayment" style="width: 100%;">
                确认收款 ¥<span class="confirm-amount">0</span>
            </button>
        </div>
    </div>
</div>
<!-- 弹窗结束 -->





    </div>


    <script>
    
                            
    layui.use(['form', 'layer', 'jquery'], function(){
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        
        // 检查会话状态
        function checkSession() {
            $.ajax({
                url: '/app/ky_shouyin/admin/account/checkSession',
                type: 'GET',
                success: function(res) {
                    if (res.code !== 0) {
                        layer.msg('会话已过期，请重新登录', {icon: 2});
                        setTimeout(function() {
                            window.location.href = '/app/ky_shouyin/admin/account/login';
                        }, 1500);
                    }
                }
            });
        }
        
        // 定期检查会话状态
        setInterval(checkSession, 60000); // 每分钟检查一次
        
        // 加载商品分类
        loadCategories();
        
        // 加载商品列表
        loadGoods();
        
        // 搜索商品
        $('#searchGoods').on('input', function(){
            var keyword = $(this).val();
            loadGoods(keyword);
        });

        // 显示收款确认弹窗
        function showPaymentConfirm(totalAmount, actualAmount, discountAmount, verifyCode) {
            // 保存购物车商品信息到全局变量
            window.cartItems = getCartItems();
            
            // 获取当前会员信息
            var memberCardNo = $('#memberCardNo').text();
            var memberName = $('#memberName').text();
            var memberBalance = parseFloat($('#memberBalance').text()) || 0;
            
            layer.open({
                type: 1,
                title: '收银结账',
                area: ['500px', '580px'],
                content: $('#paymentConfirmDialog'),
                success: function(layero, index){
                    // 更新会员信息显示
                    if (memberCardNo && memberName) {
                        $(layero).find('.member-info').show();
                        $(layero).find('.guest-info').hide();
                        $(layero).find('.member-card').text(memberCardNo);
                        $(layero).find('.member-name').text(memberName);
                        
                        // 如果会员余额充足，默认选择余额支付
                        if (memberBalance >= actualAmount) {
                            $(layero).find('.method-item[data-method="balance"]').addClass('selected')
                                .siblings().removeClass('selected');
                        }
                    } else {
                        $(layero).find('.member-info').hide();
                        $(layero).find('.guest-info').show();
                        // 非会员默认现金支付
                        $(layero).find('.method-item[data-method="cash"]').addClass('selected')
                            .siblings().removeClass('selected');
                    }
                    
                    // 如果是会员但余额不足，禁用余额支付按钮
                    if (memberCardNo && memberBalance < actualAmount) {
                        $(layero).find('.method-item[data-method="balance"]').addClass('disabled')
                            .attr('title', '余额不足');
                    }
                    
                    // 更新金额显示
                    $(layero).find('.actual-amount').val(actualAmount.toFixed(2));
                    $(layero).find('.pending-amount').text('¥' + actualAmount.toFixed(2));
                    $(layero).find('.discount-amount').text('¥' + discountAmount.toFixed(2));
                    $(layero).find('.confirm-amount').text(actualAmount.toFixed(2));
                    
                    // 绑定支付方式切换
                    $(layero).find('.method-item').click(function(){
                        // 检查是否被禁用
                        if ($(this).hasClass('disabled')) {
                            layer.msg('余额不足，请选择其他支付方式');
                            return;
                        }
                        $(layero).find('.method-item').removeClass('selected');
                        $(this).addClass('selected');
                    });

                    // 绑定数字按钮
                    $(layero).find('.num-btn').click(function(){
                        var num = $(this).data('num');
                        var $input = $(layero).find('.actual-amount');
                        var currentValue = $input.val() || '';
                        var pendingAmount = parseFloat($(layero).find('.pending-amount').text().replace('¥', '')) || 0;
                        
                        switch(num) {
                            case 'clear':
                                $input.val('0');
                                // 更新优惠金额
                                $(layero).find('.discount-amount').text('¥' + pendingAmount.toFixed(2));
                                break;
                            case 'backspace':
                                if(currentValue.length > 0) {
                                    $input.val(currentValue.slice(0, -1) || '0');
                                    // 更新优惠金额
                                    var newActual = parseFloat(currentValue.slice(0, -1)) || 0;
                                    var newDiscount = pendingAmount - newActual;
                                    $(layero).find('.discount-amount').text('¥' + newDiscount.toFixed(2));
                                }
                                break;
                            case 'enter':
                                // 触发确认收款按钮点击
                                $(layero).find('#btnConfirmPayment').click();
                                break;
                            case '.':
                                // 如果已经有小数点，则不再添加
                                if(currentValue.indexOf('.') === -1) {
                                    $input.val(currentValue + '.');
                                }
                                break;
                            default:
                                // 处理数字输入
                                if(currentValue === '0' && num !== '00') {
                                    currentValue = '';
                                }
                                // 限制小数点后两位
                                if(currentValue.indexOf('.') > -1) {
                                    var parts = currentValue.split('.');
                                    if(parts[1] && parts[1].length >= 2) {
                                        return;
                                    }
                                }
                                $input.val(currentValue + num);
                                // 更新优惠金额
                                var actualAmount = parseFloat(currentValue + num) || 0;
                                var discountAmount = pendingAmount - actualAmount;
                                $(layero).find('.discount-amount').text('¥' + discountAmount.toFixed(2));
                        }
                        
                        // 更新确认按钮上的金额显示
                        var newAmount = parseFloat($input.val()) || 0;
                        $(layero).find('.confirm-amount').text(newAmount.toFixed(2));
                    });

                    // 绑定确认收款按钮点击事件
                    $(layero).find('#btnConfirmPayment').click(function(){
                        // var selectedMethod = $(layero).find('.method-item.selected').data('method');
                        var payMethod ='balance';// selectedMethod === balance ? 'balance' : 'cash';
                               
                        confirmPayment(payMethod, verifyCode);
                    });
                }
            });
        }
        
        // 选择分类
        $('.category-bar').on('click', 'button', function(){
            $(this).addClass('layui-btn-normal').siblings().removeClass('layui-btn-normal');
            var categoryId = $(this).data('id');
            loadGoods('', categoryId);
        });
        
        // 选择商品
        $('#goodsList').on('click', '.goods-item', function(){
            var goodsId = $(this).data('id');
            var goodsName = $(this).data('name');
            var goodsPrice = $(this).data('price');
            addToCart(goodsId, goodsName, goodsPrice);
        });
        
        // 搜索会员按钮点击事件
        $('#searchMemberBtn').on('click', function() {
            var keyword = $('.search-input').val();
            if(!keyword) {
                layer.msg('请输入会员卡号或手机号');
                return;
            }
            searchMember(keyword);
        });
        
        // 开卡按钮点击事件
        $('#btnOpenCard').click(function(){
            layer.open({
                type: 2,
                title: '会员开卡',
                shade: 0.6,
                area: ['80%', '90%'],
                content: '/app/ky_shouyin/front/member/add'
            });
        });
        
        // 充值按钮点击事件
        $('#btnRecharge').click(function(){
            var cardNo = $('#memberCardNo').text();
            if(!cardNo) {
                layer.msg('请先选择会员');
                return;
            }
            layer.open({
                type: 2,
                title: '会员充值',
                shade: 0.6,
                area: ['500px', '400px'],
                content: '/app/ky_shouyin/front/member/recharge?card_no=' + cardNo
            });
        });
        
        // 修改商品数量
        $('#cartList').on('click', '.btn-quantity', function(){
            var tr = $(this).closest('tr');
            var quantity = parseInt(tr.find('.quantity').text());
            var price = parseFloat(tr.find('.price').text());
            
            if($(this).hasClass('layui-btn-primary')) {
                quantity--;
            } else {
                quantity++;
            }
            
            if(quantity < 1) {
                tr.remove();
            } else {
                tr.find('.quantity').text(quantity);
                tr.find('.subtotal').text((price * quantity).toFixed(2));
            }
            
            calculateTotal();
        });
        // 删除商品
        $('#cartList').on('click', '.btn-delete', function(){
            $(this).closest('tr').remove();
            calculateTotal();
        });
        
        // 优惠金额输入
        $('#discountAmount').on('input', function(){
            calculateTotal();
        });
        
        // 结算按钮点击事件
        $('#submitBtn').click(function(){
            var cartItems = [];
            var memberId = $('#memberId').val();
            var verifyCode = $('#verifyCode').val();
            
            // 验证是否选择了会员
            if(!memberId) {
                layer.msg('请先选择会员', {icon: 2});
                return false;
            }
            
            // 验证是否输入验证码
            if(!verifyCode) {
                layer.msg('请输入验证码', {icon: 2});
                return false;
            }
            
            // 获取购物车商品
            $('#cartList tr').each(function(){
                var $tr = $(this);
                cartItems.push({
                    goods_id: $tr.data('id'),
                    goods_name: $tr.find('td:first').text(),
                    price: parseFloat($tr.find('.price').text()),
                    quantity: parseInt($tr.find('.quantity').text()),
                    subtotal: parseFloat($tr.find('.subtotal').text())
                });
            });
            
            if(cartItems.length === 0) {
                layer.msg('请先选择商品', {icon: 2});
                return;
            }
            var totalAmount = parseFloat($('#totalAmount').val());
    var discountAmount = parseFloat($('#discountAmount').val());
    var actualAmount = parseFloat($('#actualAmount').val());
             // 显示收款确认弹窗
    showPaymentConfirm(totalAmount, actualAmount, discountAmount, verifyCode);
            
            
        });
   // 获取购物车商品信息的辅助函数
function getCartItems() {
    var items = [];
    $('#cartList tr').each(function(){
        items.push({
            goods_id: $(this).data('id'),
            goods_name: $(this).find('td:first').text(),
            quantity: parseInt($(this).find('.quantity').text()),
            price: parseFloat($(this).find('.price').text()),
            subtotal: parseFloat($(this).find('.subtotal').text())
        });
    });
    return items;
}     
        // 确认支付处理函数
        function confirmPayment(payMethod, verifyCode) {
            // 获取最新的优惠金额
            var pendingAmount = parseFloat($('.pending-amount').text().replace('¥', '')) || 0;
            var actualAmount = parseFloat($('.actual-amount').val()) || 0;
            var discountAmount = pendingAmount - actualAmount;
            
            var data = {
                member_card_no: $('#memberCardNo').text(),
                payment_method: payMethod,
                total_amount: pendingAmount,
                discount_amount: discountAmount,
                actual_amount: actualAmount,
                goods: cartItems,
                verify_code: verifyCode
            };
            
            // 提交订单
            $.ajax({
                url: '/app/ky_shouyin/front/cashier/submit-order',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(res){
                    if(res.code === 0) {
                        layer.closeAll();
                        layer.msg('结算成功');
                        clearCart();
                    } else {
                        layer.msg(res.msg || '结算失败');
                    }
                },
                error: function(){
                    layer.msg('系统错误');
                }
            });
        }
        
        
        // 加载商品分类
        function loadCategories() {
            $.get('/app/ky_shouyin/front/cashier/categories', function(res){
                if(res.code === 0) {
                    var html = '<button class="layui-btn layui-btn-primary layui-btn-sm layui-btn-normal" data-id="">全部</button>';
                    res.data.forEach(function(item){
                        html += '<button class="layui-btn layui-btn-primary layui-btn-sm" data-id="'+ item.id +'">'+ item.name +'</button>';
                    });
                    $('.category-bar').html(html);
                }
            });
        }
        
        // 加载商品列表
        function loadGoods(keyword, categoryId) {
            var params = {};
            if(keyword) params.keyword = keyword;
            if(categoryId) params.category_id = categoryId;
            
            $.get('/app/ky_shouyin/front/cashier/goods', params, function(res){
                if(res.code === 0) {
                    var html = '';
                    res.data.forEach(function(item){
                        html += '<div class="goods-item" data-id="'+ item.id +'" data-name="'+ item.name +'" data-price="'+ item.price +'">';
                        html += '<div class="goods-name">'+ item.name +'</div>';
                        html += '<div class="goods-price">￥'+ item.price +'</div>';
                        html += '</div>';
                    });
                    $('#goodsList').html(html);
                }
            });
        }
        
        // 监听查询方式切换
        form.on('radio(searchType)', function(data){
            var $input = $('.search-input');
            if(data.value === 'phone') {
                $input.val('').attr('placeholder', '请输入手机号');
            } else {
                $input.val('VIP').attr('placeholder', '请输入会员卡号');
            }
        });
        
        // 会员卡号输入处理
        $('.search-input').on('input', function(){
            var searchType = $('input[name="search_type"]:checked').val();
            if(searchType === 'card') {
                var value = $(this).val().toUpperCase();
                if(!value.startsWith('VIP')) {
                    value = 'VIP' + value.replace(/VIP/g, '');
                }
                $(this).val(value);
            }
        });
        
        // 修改搜索会员函数
        function searchMember(keyword) {
            var searchType = $('input[name="search_type"]:checked').val();
            
            if(!keyword) {
                layer.msg('请输入' + (searchType === 'phone' ? '手机号' : '会员卡号'));
                return;
            }
            
            if(searchType === 'card' && !keyword.startsWith('VIP')) {
                layer.msg('会员卡号必须以VIP开头');
                return;
            }
            
            $.get('/app/ky_shouyin/front/member/getMember', {
                search_key: keyword,
                search_type: searchType
            }, function(res){
                if (res.code === 0 && res.data) {
                    var member = res.data;
                    $('#memberId').val(member.id);
                    $('#memberCardNo').text(member.card_no);
                    $('#memberName').text(member.name);
                    $('#memberBalance').text(member.balance);
                    $('#memberPoints').text(member.points);
                    $('.member-info').show();  // 显示会员信息区域（包含验证码输入框）
                    
                    // 启用并自动选择余额支付
                    if(parseFloat(member.balance) > 0) {
                        $('input[name="payment"][value="balance"]').prop('disabled', false);
                        $('input[name="payment"][value="balance"]').prop('checked', true);
                        form.render('radio');
                    }
                } else {
                    layer.msg(res.msg || '未找到会员信息');
                    $('.member-info').hide();
                    $('input[name="payment"][value="cash"]').prop('checked', true);
                    form.render('radio');
                }
            });
        }
        
        // 添加商品到购物车
        function addToCart(goodsId, goodsName, goodsPrice) {
            var existingTr = $('#cartList tr[data-id="'+ goodsId +'"]');
            if(existingTr.length > 0) {
                var quantitySpan = existingTr.find('.quantity');
                var quantity = parseInt(quantitySpan.text()) + 1;
                quantitySpan.text(quantity);
                existingTr.find('.subtotal').text((goodsPrice * quantity).toFixed(2));
            } else {
                var html = '<tr data-id="'+ goodsId +'">';
                html += '<td>'+ goodsName +'</td>';
                html += '<td class="price">'+ goodsPrice +'</td>';
                html += '<td>';
                html += '<button class="layui-btn layui-btn-primary layui-btn-xs btn-quantity">-</button>';
                html += '<span class="quantity">1</span>';
                html += '<button class="layui-btn layui-btn-xs btn-quantity">+</button>';
                html += '</td>';
                html += '<td class="subtotal">'+ goodsPrice +'</td>';
                html += '<td><button class="layui-btn layui-btn-danger layui-btn-xs btn-delete">删除</button></td>';
                html += '</tr>';
                $('#cartList').append(html);
            }
            calculateTotal();
        }
        
        // 计算总金额
        function calculateTotal() {
            var total = 0;
            $('#cartList tr').each(function(){
                total += parseFloat($(this).find('.subtotal').text());
            });
            $('#totalAmount').val(total.toFixed(2));
            
            var discount = parseFloat($('#discountAmount').val()) || 0;
            var actualAmount = total - discount;
            $('#actualAmount').val(actualAmount.toFixed(2));
            $('.actual-amount').val(actualAmount.toFixed(2));
        }
        
        // 清空购物车
        function clearCart() {
            $('#cartList').empty();
            $('#totalAmount').val('0.00');
            $('#discountAmount').val('0');
            $('#actualAmount').val('0.00');
            $('.actual-amount').val('0.00');
            $('.search-input').val('');
            $('.member-info').hide();
            $('input[name="payment"][value="cash"]').prop('checked', true);
            $('input[name="payment"][value="balance"]').prop('disabled', true);
            form.render('radio');
        }

        // 发送验证码倒计时
        var countdown = 60;
        var timer = null;
        
        // 发送验证码
        $('#sendCode').on('click', function(){
            var $this = $(this);
            if($this.hasClass('layui-btn-disabled')) return;
            
            var memberId = $('#memberId').val();
            if(!memberId){
                layer.msg('请先选择会员', {icon: 2});
                return;
            }
            
            // 发送验证码请求
            $.ajax({
                url: '/app/ky_shouyin/front/cashier/sendVerifyCode'
                ,type: 'POST'
                ,data: {member_id: memberId}
                ,success: function(res){
                    if(res.code === 0){
                        layer.msg('验证码已发送', {icon: 1});
                        // 开始倒计时
                        $this.addClass('layui-btn-disabled');
                        timer = setInterval(function(){
                            if(countdown > 0){
                                $this.text(countdown + '秒后重发');
                                countdown--;
                            }else{
                                clearInterval(timer);
                                $this.removeClass('layui-btn-disabled').text('发送验证码');
                                countdown = 60;
                            }
                        }, 1000);
                    }else{
                        layer.msg(res.msg, {icon: 2});
                    }
                }
            });
        });

        // 选择会员后显示验证码区域
        function selectMember(data){
            // 原有的会员信息显示代码...
            $('.member-info').show();
        }
        
        // 提交订单前验证
        form.on('submit(submitOrder)', function(data){
            var verifyCode = $('#verifyCode').val();
            if(!verifyCode){
                layer.msg('请输入验证码', {icon: 2});
                return false;
            }
            
            // 添加验证码到提交数据
            data.field.verify_code = verifyCode;
            
            // 提交订单...
        });
    });
    </script>
</body>
</html>
